﻿using CefSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CefSharpWinformDemo
{
    public partial class Form1 : Form
    {
        private const int CLOSE_SIZE = 15;

        public Form1()
        {
            InitializeComponent();

            this.tabControl.Padding = new Point(CLOSE_SIZE - 3, 0); //关闭按钮不遮挡文字
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //CreateTabItem("https://www.cnblogs.com/");
            CreateTabItem("file:///D:/_程序/CefSharpWinformDemo/post.html");

            AddNewPageBtn(); //创建新标签页button按钮
        }

        #region 创建新标签页button按钮
        /// <summary>
        /// 创建新标签页button按钮
        /// </summary>
        private void AddNewPageBtn()
        {
            int btnWidth = 75;
            int btnHeight = 22;
            Button btn = new Button();
            btn.Location = new Point(this.Width - btnWidth - 19, 0);
            btn.Size = new Size(btnWidth, btnHeight);
            btn.Name = "btnNewPage";
            btn.Text = "新标签页";
            btn.Click += btnNewPage_Click;
            this.SizeChanged += new EventHandler((s, e) =>
            {
                btn.Location = new Point(this.Width - btnWidth - 19, 0);
            });
            this.Controls.Add(btn);
            btn.BringToFront();
        }
        #endregion

        #region btnNewPage_Click
        private void btnNewPage_Click(object sender, EventArgs e)
        {
            CreateTabItem("https://www.cnblogs.com/");
        }
        #endregion

        #region CreateTabItem 新增Tab页
        /// <summary>
        /// 新增Tab页
        /// </summary>
        private void CreateTabItem(string url, NewWindowEventArgs args = null, bool addToLast = true)
        {
            TabPage tabItem = new TabPage();
            tabItem.Text = "新标签页";
            this.tabControl.DrawMode = TabDrawMode.OwnerDrawFixed;
            BrowserDemoCtrl ctrl = new BrowserDemoCtrl(url);
            ctrl.Dock = DockStyle.Fill;
            ctrl.browserCtrl.Browser.StartNewWindow += (s, e) =>
            {
                CreateTabItem(e.TargetUrl, e, false);
            };
            tabItem.Controls.Add(ctrl);
            if (addToLast)
            {
                tabControl.TabPages.Add(tabItem);
            }
            else
            {
                if (tabControl.SelectedIndex >= 0)
                {
                    tabControl.TabPages.Insert(tabControl.SelectedIndex + 1, tabItem);
                }
                else
                {
                    tabControl.TabPages.Add(tabItem);
                }
            }
            tabControl.SelectedTab = tabItem;
            tabItem.BringToFront();
            if (args != null)
            {
                args.NewBrowser = ctrl.browserCtrl.Browser;
            }
            else
            {
                ctrl.browserCtrl.LoadUrl(url);
            }
        }
        #endregion

        #region tabControl_DrawItem
        /// <summary>
        /// 重新绘制page页
        /// 版权声明：本文为CSDN博主「你懂的11」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
        /// 原文链接：https://blog.csdn.net/u012408847/article/details/88423096
        /// </summary>
        private void tabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            //如果将 DrawMode 属性设置为 OwnerDrawFixed， 
            //则每当 TabControl 需要绘制它的一个选项卡时，它就会引发 DrawItem 事件
            try
            {
                TabPage tabPage = this.tabControl.TabPages[e.Index];
                tabPage.BackColor = this.BackColor;
                Rectangle tabRect = this.tabControl.GetTabRect(e.Index);
                e.Graphics.DrawString(tabPage.Text, this.Font, SystemBrushes.ControlText, (float)(tabRect.X + 2), (float)(tabRect.Y + 2));
                using (Pen pen = new Pen(Color.Transparent))
                {
                    tabRect.Offset(tabRect.Width - CLOSE_SIZE, 2);
                    tabRect.Width = CLOSE_SIZE;
                    tabRect.Height = CLOSE_SIZE;
                    e.Graphics.DrawRectangle(pen, tabRect);
                }
                Color color = (e.State == DrawItemState.Selected) ? Color.White : this.BackColor;
                using (Brush brush = new SolidBrush(color))
                {
                    e.Graphics.FillRectangle(brush, tabRect);
                }
                using (Pen pen2 = new Pen(Color.Red, 1))
                {
                    Point point = new Point(tabRect.X + 3, tabRect.Y + 3);
                    Point point2 = new Point((tabRect.X + tabRect.Width) - 3, (tabRect.Y + tabRect.Height) - 3);
                    e.Graphics.DrawLine(pen2, point, point2);
                    Point point3 = new Point(tabRect.X + 3, (tabRect.Y + tabRect.Height) - 3);
                    Point point4 = new Point((tabRect.X + tabRect.Width) - 3, tabRect.Y + 3);
                    e.Graphics.DrawLine(pen2, point3, point4);
                }
                e.Graphics.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region tabControl_MouseDown
        /// <summary>
        /// 鼠标点击选项卡时的触发
        /// 原文链接：https://www.cnblogs.com/chcong/p/4312651.html
        /// </summary>
        private void tabControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                try
                {
                    int x = e.X, y = e.Y;

                    //计算关闭区域   
                    Rectangle myTabRect = this.tabControl.GetTabRect(this.tabControl.SelectedIndex);

                    myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                    myTabRect.Width = CLOSE_SIZE;
                    myTabRect.Height = CLOSE_SIZE;

                    //如果鼠标在区域内就关闭选项卡,如果不在就显示选项卡
                    //如果关闭的选项卡正好打开着，则关闭当前先项卡，显示下一个选项卡
                    bool isClose = x > myTabRect.X && x < myTabRect.Right && y > myTabRect.Y && y < myTabRect.Bottom;
                    int selectedIndex = this.tabControl.SelectedIndex;
                    if (isClose == true)
                    {
                        selectedIndex = this.tabControl.SelectedIndex - 1;
                        Control selectedCtrl = this.tabControl.SelectedTab.Controls[0];
                        this.tabControl.TabPages.Remove(this.tabControl.SelectedTab);
                        if (selectedCtrl is IDisposable)
                        {
                            (selectedCtrl as IDisposable).Dispose(); //释放资源
                        }
                    }

                    if (selectedIndex < 0) selectedIndex = 0;

                    //显示页面
                    if (this.tabControl.TabPages.Count > 0)
                    {
                        this.tabControl.SelectedTab = this.tabControl.TabPages[selectedIndex];
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        #endregion

    }
}
